//
//  main.swift
//  20.泛型
//
//  Created by 左忠飞 on 2021/10/13.
//

import Foundation

func swapTwoValue<T>(_ a:inout T,_ b:inout T) {
    let temp = a
    a = b
    b = temp
}

var inta = 1
var intb = 2
swapTwoValue(&inta, &intb)
print("a = \(inta),b = \(intb)")


//泛型栈
struct Stack<Element> {
    var items = [Element]()
    mutating func push(_ item:Element){
        items.append(item)
    }
    
    mutating func pop() -> Element {
        return items.removeLast()
    }
}

var stackOfString = Stack<String>()
stackOfString.push("hello")
stackOfString.push("world")
stackOfString.push("i")
stackOfString.push("like")
stackOfString.push("swift")

print(stackOfString.pop())
print(stackOfString.pop())
print(stackOfString.pop())
print(stackOfString.pop())

//扩展泛型类型
extension Stack{
    var topItem:Element?{
        return items.isEmpty ? nil : items[items.count - 1]
    }
}

print(stackOfString.topItem ?? "")


//泛型约束,泛型类型只能是在约束范围内的类型
func findIndex<T:Equatable>(of valueToFind:T,in array:[T]) -> Int?{
    for(index,value) in array.enumerated(){
        if value == valueToFind {
            return index
        }
    }
    return nil
}
//泛型T必须是实现Equatable协议的类型,只有实现了这个协议的类型才可以使用 == 操作符进行比较.

let array1 = [1,2,3,4,5,6]
let index = findIndex(of: 3, in: array1)
print(index ?? 0)

let array2 = ["a","b","c","d","e","f"]
let index2 = findIndex(of: "b", in: array2)
print(index2 ?? 0)


//关联类型协议
